from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from apps.cards.models import Card, UserCard

User = get_user_model()


class Command(BaseCommand):
    help = '给用户初始卡牌'

    def add_arguments(self, parser):
        parser.add_argument('--username', type=str, help='用户名')
        parser.add_argument('--all', action='store_true', help='给所有用户初始卡牌')

    def handle(self, *args, **options):
        if options['all']:
            users = User.objects.all()
        elif options['username']:
            try:
                users = [User.objects.get(username=options['username'])]
            except User.DoesNotExist:
                self.stdout.write(
                    self.style.ERROR(f'用户 {options["username"]} 不存在')
                )
                return
        else:
            self.stdout.write(
                self.style.ERROR('请指定 --username 或 --all')
            )
            return

        # 获取一些基础卡牌
        initial_cards = Card.objects.filter(
            name__in=['火球术', '冰箭术', '闪电术', '治疗术', '护盾术']
        )

        for user in users:
            self.stdout.write(f'给用户 {user.username} 添加初始卡牌...')
            
            for card in initial_cards:
                user_card, created = UserCard.objects.get_or_create(
                    user=user,
                    card=card,
                    defaults={'quantity': 2}  # 每张卡给2张
                )
                if created:
                    self.stdout.write(
                        self.style.SUCCESS(f'  - 添加 {card.name} x2')
                    )
                else:
                    self.stdout.write(
                        self.style.WARNING(f'  - {card.name} 已存在')
                    )

        self.stdout.write(
            self.style.SUCCESS(f'成功为 {len(users)} 个用户添加初始卡牌')
        )
